<?php
/**
 *
 * User: 罗艳忠
 * Email:luozong05@126.com
 * DateTime: 2017/5/3 16:49
 */

namespace App\Http\Controllers;
use App\Models\Config;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Libraries\EasyClass;
use EasyWeChat\Foundation\Application as  EasyWeChat;

class ConfigController extends Controller
{
    function __construct(Request $request){
        parent::__construct();
        $this->request = $request;
    }

    public function config(){
        $module = $this->request->module;
        return view("config_".$module,['module'=>$module,'config'=>$this->config]);
    }
    public function save(){
        $module = $this->request->get("module");
        $rules = [
            //'module' =>  'wechat' ,
            'wechat_name' =>  'required' ,
            'wechat_id' =>  'required',
            'wechat_no' =>  'required' ,
            'wechat_appid' =>  'required',
            'wechat_appsecret' =>  'required',
            'wechat_qr' =>  'required',
            'wechat_type' =>  'required',
            'to_kf_keyword' =>  'required',
            'wechat_token' =>  'required',
        ];
        $validator = Validator::make($this->request->all(), $rules);
        if ( $validator->fails() ) {
            return redirect("config/".$module)
                ->withErrors($validator)
                ->withInput();
        }
        $data = $this->request->only("wechat_name","wechat_id",'wechat_no','wechat_appid','wechat_appsecret','wechat_qr','wechat_type','to_kf_keyword','wechat_token');

        if(!isset($this->config[$module]['wechat_token'])||empty($this->config[$module]['wechat_token'])){
            $this->config[$module]['wechat_token'] = ucwords(md5(microtime()));
        }

        //$data["wechat_token"] = $wechat->access_token->getToken();
        $data = json_encode(array_map("base64_encode", array_merge($this->config[$module], $data)));

        if( Config::where("mod", $module)->update(["config"=>$data])){
            return redirect("config/".$module);
        }else{
            return back();
        }
    }

}